<template>
  <div class="app-container">
    <el-form
      v-show="showSearch"
      ref="queryForm"
      :model="queryParams"
      :inline="true"
    >
      <el-form-item label="任务名称" prop="missionName">
        <el-input
          v-model="queryParams.missionName"
          placeholder="请输入角色名称"
          clearable
          size="small"
          style="width: 240px"
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="任务状态" prop="status">
        <el-select
          v-model="queryParams.status"
          placeholder="任务状态"
          clearable
          size="small"
          style="width: 240px"
        >
          <!-- // wait  running  done error -->
          <el-option label="所有" value="" />
          <el-option label="待执行" value="wait" />
          <el-option label="执行中" value="running" />
          <el-option label="完成" value="done" />
          <el-option label="错误" value="error" />
        </el-select>
      </el-form-item>
      <el-form-item>
        <el-button
          type="primary"
          icon="el-icon-search"
          size="mini"
          @click="handleQuery"
          >搜索</el-button
        >
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery"
          >重置</el-button
        >
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          v-hasPermi="['system:role:add']"
          type="primary"
          plain
          icon="el-icon-plus"
          size="mini"
          @click="handleAdd"
          >新增</el-button
        >
      </el-col>
      <el-col :span="1.5">
        <el-button
          v-hasPermi="['system:role:edit']"
          type="success"
          plain
          icon="el-icon-edit"
          size="mini"
          :disabled="single"
          @click="handleUpdate"
          >修改</el-button
        >
      </el-col>
      <el-col :span="1.5">
        <el-button
          v-hasPermi="['system:role:remove']"
          type="danger"
          plain
          icon="el-icon-delete"
          size="mini"
          :disabled="multiple"
          @click="handleDelete"
          >删除</el-button
        >
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="warning"
          plain
          icon="el-icon-download"
          size="mini"
          :loading="exportLoading"
          @click="handleExport"
          >导出</el-button
        >
      </el-col>
      <right-toolbar :show-search.sync="showSearch" @queryTable="getList" />
    </el-row>

    <el-table
      v-loading="loading"
      :data="roleList"
      @selection-change="handleSelectionChange"
    >
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column label="任务名称" prop="missionName" width="120" />
      <el-table-column
        label="任务状态"
        prop="status"
        :show-overflow-tooltip="true"
        :formatter="statusFormat"
        width="150"
      />

      <el-table-column
        label="开始时间"
        align="center"
        prop="startTime"
        width="180"
      >
        <template slot-scope="scope">
          <span>{{ parseTime(scope.row.createTime) }}</span>
        </template>
      </el-table-column>
      <el-table-column
        label="结束时间"
        align="center"
        prop="endTime"
        width="200"
      >
        <template slot-scope="scope">
          <span>{{ parseTime(scope.row.createTime) }}</span>
        </template>
      </el-table-column>
      <el-table-column label="爬取时间(s)" prop="timeCost" width="100" />
      <el-table-column
        label="退出方式"
        prop="exitWay"
        width="100"
        :formatter="exitWayFormat"
      />
      <el-table-column
        label="操作"
        align="center"
        class-name="small-padding fixed-width"
      >
        <template slot-scope="scope">
          <el-button
            size="mini"
            type="primary"
            icon="el-icon-edit"
            @click="handleUpdate(scope.row)"
            >编辑</el-button
          >
          <el-popconfirm
            title="确认要运行爬虫吗？"
            @confirm="confirm(scope.row)"
          >
            <el-button
              slot="reference"
              size="mini"
              type="warning"
              icon="el-icon-circle-check"
              >运行爬虫</el-button
            >
          </el-popconfirm>

          <el-button
            size="mini"
            type="danger"
            icon="el-icon-delete"
            @click="handleDelete(scope.row)"
            >删除</el-button
          >
        </template>
      </el-table-column>
    </el-table>

    <pagination
      v-show="total > 0"
      :total="total"
      :page.sync="queryParams.pageNum"
      :limit.sync="queryParams.pageSize"
      @pagination="getList"
    />

    <!-- 修改任务抽屉 -->
    <el-drawer
      ref="drawer"
      :title="title"
      :visible.sync="open"
      direction="rtl"
      size="50%"
      custom-class="demo-drawer"
    >
      <div class="demo-drawer__content">
        <el-form :model="form">
          <el-form-item label="任务名称：">
            <el-input v-model="form.missionName" autocomplete="off" />
          </el-form-item>
          <div class="config">
            <el-form-item label="爬虫配置：">
              <el-input
                v-model="form.spiderName"
                autocomplete="off"
                @click.native="toggleEdit"
              />
            </el-form-item>
          </div>
          <el-form-item label="入口地址：">
            <el-input v-model="form.entryUrls" type="textarea" />
          </el-form-item>
          <el-form-item label="Cookie：">
            <el-input v-model="form.cookieStr" type="textarea" />
          </el-form-item>
          <el-form-item label="Header：">
            <el-input v-model="form.headerStr" type="textarea" />
          </el-form-item>
          <el-form-item label="退出方式：">
            <el-radio-group v-model="form.exitWay">
              <el-radio label="默认" />
              <el-radio label="持续时间" />
              <el-radio label="链接计数" />
            </el-radio-group>
          </el-form-item>
          <el-form-item label="退出值：">
            <el-input v-model="form.exitWayCount" autocomplete="off" />
          </el-form-item>
        </el-form>
        <div class="demo-drawer__footer">
          <el-button @click="cancelForm">取 消</el-button>
          <el-button type="primary" :loading="loading" @click="editTask()">{{
            loading ? "提交中 ..." : "确 定"
          }}</el-button>
        </div>
      </div>
    </el-drawer>
    <!-- 配置选择对话框 -->
    <el-dialog
      title="爬虫配置选择"
      :visible.sync="openDataScope"
      width="50%"
      append-to-body
    >
      <el-form :model="configForm" label-width="80px" :inline="true">
        <el-form-item label="爬虫编码">
          <el-input v-model="configForm.spiderCode" />
        </el-form-item>
        <el-form-item label="爬虫名称">
          <el-input v-model="configForm.spiderName" />
        </el-form-item>
        <el-form-item>
          <el-button
            type="primary"
            icon="el-icon-search"
            size="mini"
            @click="handleConfigQuery"
            >搜索</el-button
          >
          <el-button
            icon="el-icon-refresh"
            size="mini"
            @click="resetConfigQuery"
            >重置</el-button
          >
        </el-form-item>
      </el-form>
      <el-table
        ref="tb"
        :data="configList"
        @selection-change="handleConfigChange"
      >
        <el-table-column type="selection" width="55" align="center" />
        <el-table-column
          label="爬虫编码"
          prop="spiderCode"
          :show-overflow-tooltip="true"
          width="150"
        />
        <el-table-column
          label="爬虫名称"
          prop="spiderName"
          :show-overflow-tooltip="true"
          width="150"
        />
        <el-table-column label="字符集" prop="charset" width="100" />
        <el-table-column
          label="睡眠时间"
          align="center"
          prop="sleepTime"
          width="180"
        >
          <template slot-scope="scope">
            <span>{{ parseTime(scope.row.createTime) }}</span>
          </template>
        </el-table-column>
        <el-table-column label="线程数量" prop="threadCount" width="100" />
        <el-table-column label="使用代理" prop="useProxy" width="100"
          ><template slot-scope="scope">
            <span>{{ scope.row.useProxy === 0 ? "不使用" : "使用代理" }}</span>
          </template></el-table-column
        >
      </el-table>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitDataScope">确 定</el-button>
        <el-button @click="cancelDataScope">取 消</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import {
  taskList,
  updateTask,
  delTask,
  startTask,
  addTask,
  configTask,
  exportTask,
  getTask
} from '@/api/spider/task'

export default {
  name: 'Role',
  data() {
    return {
      // 遮罩层
      loading: true,
      // 导出遮罩层
      exportLoading: false,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 角色表格数据
      roleList: [],
      configList: [],
      // 弹出层标题
      title: '',
      // 是否显示弹出层
      open: false,
      // 是否显示弹出层（数据权限）
      openDataScope: false,
      menuExpand: false,
      menuNodeAll: false,
      deptExpand: true,
      deptNodeAll: false,
      // 状态数据字典
      statusOptions: [],
      // 菜单列表
      menuOptions: [],
      // 部门列表
      deptOptions: [],
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        missionName: undefined,
        status: undefined
      },
      // 表单参数
      form: {},
      configForm: {},
      defaultProps: {
        children: 'children',
        label: 'label'
      },
      // 表单校验
      rules: {},
      spiderName: '',
      selection: []
    }
  },
  created() {
    this.getList()
    const data = {
      pageSize: 10,
      pageNum: 1,
      isAsc: 'asc'
    }
    this.getConfigList(data)
    getTask()
  },
  methods: {
    getConfigList(data) {
      configTask(data).then(res => {
        this.configList = res.list
      })
    },
    editTask() {
      this.$refs.drawer.closeDrawer()
      const exitWay =
        this.form.exitWay === '持续时间'
          ? 'DURATION'
          : this.form.exitWay === '默认'
            ? 'DEFAULT'
            : 'URL_COUNT'
      this.form.exitWay = exitWay
      if (this.title === '修改爬虫任务') {
        updateTask(this.form).then(res => {
          if (res.code === 200) {
            this.msgSuccess('修改成功')
            this.getList()
          }
        })
      } else {
        delete this.form['missionId']
        addTask(this.form).then(res => {
          if (res.code === 200) {
            this.msgSuccess('新增成功')
            this.getList()
          }
        })
      }
    },
    cancelForm() {
      this.loading = false
      this.open = false
    },
    // wait  running  done error
    statusFormat(row, column) {
      switch (row.status) {
        case 'wait':
          return '待执行'
        case 'running':
          return '执行中'
        case 'done':
          return '完成'
        case 'error':
          return '错误'
        default:
          break
      }
    },

    exitWayFormat(row, column) {
      switch (row.exitWay) {
        case 'DURATION':
          return '持续时间'
        case 'DEFAULT':
          return '默认'
        case 'URL_COUNT':
          return '链接计数'
        default:
          break
      }
    },
    confirm(row) {
      startTask({ missionId: row.missionId }).then(res => {
        if (res.code === 200) {
          this.getList()
        }
      })
    },
    handleConfigQuery() {
      const data = {
        pageSize: 10,
        pageNum: 1,
        isAsc: 'asc',
        spiderCode: this.configForm.spiderCode,
        spiderName: this.configForm.spiderName
      }
      this.getConfigList(data)
    },
    toggleEdit() {
      console.log(1111)
      this.openDataScope = true
    },
    /** 查询角色列表 */
    getList(value) {
      this.loading = true
      console.log('-------', this.queryParams, value)
      taskList(this.queryParams).then(response => {
        this.roleList = response.list
        this.total = response.total
        this.loading = false
      })
    },

    // 取消按钮
    cancel() {
      this.open = false
      this.reset()
    },
    // 取消按钮（数据权限）
    cancelDataScope() {
      this.openDataScope = false
      this.reset()
    },
    // 表单重置
    reset() {
      if (this.$refs.menu != undefined) {
        this.$refs.menu.setCheckedKeys([])
      }
      (this.menuExpand = false),
      (this.menuNodeAll = false),
      (this.deptExpand = true),
      (this.deptNodeAll = false),
      this.resetForm('form')
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1
      this.getList()
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm('queryForm')
      this.handleQuery()
    },
    resetConfigQuery() {
      const data = {
        pageSize: 10,
        pageNum: 1,
        isAsc: 'asc'
      }
      this.getConfigList(data)
      this.resetForm('configForm')
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.missionId)

      this.single = selection.length != 1
      this.multiple = !selection.length
    },

    handleConfigChange(selection) {
      if (selection.length > 0 && selection.length <= 1) {
        this.form.spiderName = selection[0].spiderName
        this.form.spiderConfigId = selection[0].id
      }
      this.selection = selection
    },

    /** 新增按钮操作 */
    handleAdd() {
      this.open = true
      this.resetForm('form')
      this.form = {}
      this.title = '添加爬虫任务'
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset()
      this.open = true
      const exitWay =
        row.exitWay === 'DURATION'
          ? '持续时间'
          : row.exitWay === 'DEFAULT'
            ? '默认'
            : '链接计数'
      let spiderName = ''
      this.configList.map(item => {
        if (row.spiderConfigId === item.id) {
          return (spiderName = item.spiderName)
        }
      })
      this.form = {
        missionName: row.missionName,
        spiderConfigId: row.spiderConfigId,
        spiderName,
        exitWayCount: row.exitWayCount,
        exitWay,
        headerStr: row.headerStr,
        cookieStr: row.cookieStr,
        entryUrls: row.entryUrls,
        missionId: row.missionId
      }

      this.title = '修改爬虫任务'
    },
    /** 修改爬虫任务 */
    submitDataScope() {
      console.log(this.selection)
      if (this.selection.length > 1) {
        this.msgError('只能选择一个配置')
      } else {
        this.openDataScope = false
        this.$refs.tb.clearSelection()
      }
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const missionId = row.missionId || this.ids.join(',')
      console.log(missionId, { ids: missionId })
      this.$confirm(
        '是否确认删除任务编号为"' + missionId + '"的数据项?',
        '警告',
        {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }
      )
        .then(function() {
          return delTask({ ids: missionId })
        })
        .then(() => {
          this.getList()
          this.msgSuccess('删除成功')
        })
        .catch(() => {})
    },
    /** 导出按钮操作 */
    handleExport() {
      const searchParams = this.queryParams
      this.$confirm('是否确认导出所有数据项?', '警告', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      })
        .then(() => {
          this.exportLoading = true
          return exportTask(searchParams)
        })
        .then(response => {
          this.download(response.msg)
          this.exportLoading = false
        })
        .catch(() => {})
    }
  }
}
</script>
<style scoped lang='scss'>
.demo-drawer__content {
  padding: 0 16%;
}
.config {
  ::v-deep .el-input__inner {
    background: #eee;
  }
}
::v-deep .el-popover__reference-wrapper {
  margin: 0 10px;
}
</style>
